import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';

class User {
  String token;
  String? nickname;

  String? phone;
  String? wxAppId;
  String? address;

  static User? current;

  Map? info;

  static get isLogin {
    return User.current != null;
  }

  User(this.token, this.phone);

  static Future<User?> setup() async {
    if (User.current != null) {
      return User.current;
    }

    final prefs = await SharedPreferences.getInstance();
    final str = prefs.getString('user');
    if (str != null) {
      dynamic map = jsonDecode(str);
      User.current = User(map["token"], map["phone"]);
    }

    return User.current;
  }

  static logout() async {
    if (User.current != null) {
      final prefs = await SharedPreferences.getInstance();
      prefs.remove("user");
      User.current = null;
    }
  }

  static login(map) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(
        "user", jsonEncode({"token": map["token"], "phone": map["phone"]}));
    User.current = User(map["token"], map["phone"]);
  }
}
